<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 组件重复了，封装复用 -->
        <TreeTools
          :tree-node="company"
          :is-root="true"
          class="header"
          @addDep="addDepFn"
          @edit="editDeptFn"
        />
        <el-tree :data="depts" default-expand-all :props="defaultProps">
          <!-- data是传出来的每个节点的数据 -->
          <template v-slot="{ data }">
            <TreeTools
              :tree-node="data"
              @updateDeps="getDepartments"
              @addDep="addDepFn"
            />
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- sync数据双向绑定 -->
    <AddDep
      :visible.sync="addVisible"
      :current-node="currentNode"
      :origin-deps="originDeps"
    />
  </div>
</template>

<script>
import TreeTools from './components/TreeTools.vue'
import { getDepartments } from '@/api/department.js'
import { tranListToTreeData } from '@/utils/index'
import AddDep from './/components/AddDep'
export default {
  components: { TreeTools, AddDep },
  data() {
    return {
      company: {},
      // defaultProps是定义树解构里的属性名
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      depts: [],
      addVisible: false,
      currentNode: {},
      originDeps: []
    }
  },

  created() {
    this.getDepartments()
  },

  methods: {
    async getDepartments() {
      const res = await getDepartments()
      // console.log(res)
      this.originDeps = res.depts
      this.depts = tranListToTreeData(res.depts, '')

      this.company = { name: res.companyName, manager: '负责人', children: this.depts }
    },
    addDepFn(currentNode) {
      // console.log('增加部门')
      this.addVisible = true
      this.currentNode = currentNode
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 60px;
  font-size: 14px;
}
.header {
  height: 30px;
}
</style>
